<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="80px"
    v-loading="formLoading"
  >
    <el-form-item :label="t('profile.password.oldPassword')" prop="oldPassword">
      <InputPassword v-model.trim="formData.oldPassword" />
    </el-form-item>
    <el-form-item :label="t('profile.password.newPassword')" prop="newPassword">
      <InputPassword v-model.trim="formData.newPassword" strength />
    </el-form-item>
    <el-form-item :label="t('profile.password.confirmPassword')" prop="confirmPassword">
      <InputPassword v-model.trim="formData.confirmPassword" strength />
    </el-form-item>
    <el-form-item>
      <XButton :title="t('common.save')" type="primary" @click="submitForm()" />
      <XButton :title="t('common.reset')" type="danger" @click="reset()" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { InputPassword } from '@/components/InputPassword'
import { updateUserPassword } from '@/api/system/user/profile'
import { useI18n } from 'vue-i18n'
import { reactive, ref } from 'vue'

defineOptions({ name: 'ResetPwd' })
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const { t } = useI18n()
const message = useMessage()
const formRef = ref()
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const equalToPassword = (_rule, value, callback) => {
  if (formData.value.newPassword !== value) {
    message.error(t('profile.password.diffPwd'))
  }
  callback()
}

const equalToPasswordV2 = (_rule, _value, callback) => {
  if (formData.value.oldPassword && formData.value.newPassword) {
    if (formData.value.oldPassword === formData.value.newPassword) {
      message.error(t('profile.password.oldNewConsistent'))
    }
  }
  callback()
}

// 表单校验
const formRules = reactive({
  oldPassword: [{ required: true, message: t('profile.password.oldPwdMsg'), trigger: 'blur' }],
  newPassword: [
    { required: true, message: t('profile.password.newPwdMsg'), trigger: 'blur' },
    { min: 6, max: 20, message: t('profile.password.pwdRules'), trigger: 'blur' },
    { required: true, validator: equalToPasswordV2, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.password.cfPwdMsg'), trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await updateUserPassword(formData.value.oldPassword, formData.value.newPassword)
    // 发送操作成功的事件
    message.success('修改成功')
    reset()
  } finally {
    formLoading.value = false
  }
}
const reset = () => {
  formData.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  formRef.value?.resetFields()
}
</script>
